import datetime
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
import os
from Hook import hook
from flask import Blueprint, request, redirect, make_response
from werkzeug.security import check_password_hash, generate_password_hash

from model import UserModel, EnterpriseModel, HRModel, JobModel, AdminModel, HomeMenuModel, UserAndJobModel

from home import db

from datetime import datetime, timedelta

import jwt
from flask import current_app
from home import redisDB
from home.config import BASE_DIR
import time

bp = Blueprint("auth", __name__, url_prefix="/auth")


# 获取岗位所属行业菜单
@bp.route("/getJobIndustry", methods=["POST"])
def getJobIndustry():
    msg = {
        "message": "",
        "type": "",
        "code": "",
        "job_industry": []
    }
    try:
        msg["job_industry"] = jobIndustryMenuTrees("0")

        msg["message"] = "获取成功"
        msg["code"] = "200"
        msg["type"] = "success"
    except SQLAlchemyError as e:
        msg["message"] = "获取失败"
        msg["type"] = "error"
        msg["code"] = "500"
        print(e)
    return msg


@bp.route("/getFilterEs", methods=["POST"])
def getFilterEs():
    msg = {
        "message": "",
        "type": "",
        "es": [],
        "code": "",
    }
    from Hook.hook import filterEData
    wd = request.json["wd"]["_value"]
    eData = filterEData(request.json)
    enterpriseModel = EnterpriseModel.query.all()
    if enterpriseModel:
        for i in enterpriseModel:
            if wd.lower() in i.businessName.lower() and i.eId not in msg["es"]:
                if eData["eNature"] in i.nature and eData["eSize"] in i.size:
                    msg["es"].append(
                        {
                            "eId": i.eId,
                            "eNature": i.nature,
                            "eSizeMin": i.size.split("-")[0],
                            "eSizeMax": i.size.split("-")[1],
                            "eIndustry": i.industry,
                            "contactAddress": i.contactAddress,
                            "businessName": i.businessName,
                        })
        msg["message"] = "获取成功"
        msg["type"] = "success"
        msg["code"] = "200"

    else:
        msg["message"] = "没有企业信息"
        msg["type"] = "error"
        msg["es"] = []
        msg["code"] = "500"
    return msg


# 查询公司
@bp.route("/searchEnterprises", methods=["POST"])
def searchEnterprises():
    msg = {
        "message": "",
        "type": "",
        "es": [],
        "code": "",
    }
    wd = request.json["wd"]
    enterpriseModel = EnterpriseModel.query.all()
    if enterpriseModel:
        for i in enterpriseModel:
            if wd["_value"] in i.businessName and i.eId not in msg["es"]:
                msg["es"].append(
                    {
                        "eId": i.eId,
                        "eNature": i.nature,
                        "eSizeMin": i.size.split("-")[0],
                        "eSizeMax": i.size.split("-")[1],
                        "eIndustry": i.industry,
                        "contactAddress": i.contactAddress,
                        "businessName": i.businessName,
                    })
                msg["message"] = "获取成功"
                msg["type"] = "success"
                msg["code"] = "200"

    else:
        msg["message"] = "没有企业信息"
        msg["type"] = "error"
        msg["es"] = []
        msg["code"] = "500"
    return msg


# 查询岗位-条件
@bp.route("/getFilterJobs", methods=["POST"])
def getFilterJobs():
    msg = {
        "message": "",
        "type": "",
        "jobs": [],
        "code": "",
    }
    wd = request.json["wd"]["_value"]

    from Hook.hook import filterJobData

    jobData = filterJobData(request.json)

    jobModel = JobModel.query.all()
    # print(len(jobModel))
    if jobModel:
        for i in jobModel:

            if i.isPublishing == "true":
                if wd.lower() in i.jobName.lower() or wd.lower() in i.jobIndustry.lower() and i.jobId not in msg[
                    "jobs"]:
                    if jobData["jobAddress"] == " ":
                        if jobData["jobIndustry"] in i.jobIndustry and jobData[
                            "jobNature"] in i.jobNature and jobData["jobEdu"] in i.jobEdu and jobData[
                            "jobEx"] in i.jobEx:
                            msg["jobs"].append({
                                "jobId": i.jobId,
                                "jobName": i.jobName,
                                "jobNature": i.jobNature,
                                "jobEdu": i.jobEdu,
                                "jobAge": i.jobAge,
                                "jobEx": i.jobEx,
                                "jobAddress": i.jobAddress,
                                "jobSalary": i.jobSalary,
                                "contactAddress": i.hr_list[0].e_hr.contactAddress,
                                "eName": i.hr_list[0].e_hr.businessName,
                                "eId": i.hr_list[0].e_hr.eId,
                            })
                    else:
                        if jobData["jobAddress"] in i.jobAddress and jobData["jobIndustry"] in i.jobIndustry and \
                                jobData[
                                    "jobNature"] in i.jobNature and jobData["jobEdu"] in i.jobEdu and jobData[
                            "jobEx"] in i.jobEx:
                            msg["jobs"].append({
                                "jobId": i.jobId,
                                "jobName": i.jobName,
                                "jobNature": i.jobNature,
                                "jobEdu": i.jobEdu,
                                "jobAge": i.jobAge,
                                "jobEx": i.jobEx,
                                "jobAddress": i.jobAddress,
                                "jobSalary": i.jobSalary,
                                "contactAddress": i.hr_list[0].e_hr.contactAddress,
                                "eName": i.hr_list[0].e_hr.businessName,
                                "eId": i.hr_list[0].e_hr.eId,
                            })

        msg["message"] = "获取成功"
        msg["type"] = "success"
        msg["code"] = "200"
    else:
        msg["message"] = "没有相关岗位"
        msg["type"] = "error"
        msg["jobs"] = []
        msg["code"] = "500"

    return msg


# 查询岗位
@bp.route("/searchJobs", methods=["POST"])
def searchJobs():
    msg = {
        "message": "",
        "type": "",
        "jobs": [],
        "code": "",
    }
    wd = request.json["wd"]["_value"]
    jobModel = JobModel.query.all()
    if jobModel:
        for i in jobModel:
            if i.isPublishing == "true":
                if wd.lower() in i.jobName.lower() or wd.lower() in i.jobIndustry.lower() and i.jobId not in msg[
                    "jobs"]:
                    msg["jobs"].append({
                        "jobId": i.jobId,
                        "jobName": i.jobName,
                        "jobEdu": i.jobEdu,
                        "jobAge": i.jobAge,
                        "jobEx": i.jobEx,
                        "jobAddress": i.jobAddress,
                        "jobSalary": i.jobSalary,
                        "jobNature": i.jobNature,
                        "contactAddress": i.hr_list[0].e_hr.contactAddress,
                        "eName": i.hr_list[0].e_hr.businessName,
                        "eId": i.hr_list[0].e_hr.eId,
                    })
                    msg["message"] = "获取成功"
                    msg["type"] = "success"
                    msg["code"] = "200"
    else:
        msg["message"] = "没有相关岗位"
        msg["type"] = "error"
        msg["jobs"] = []
        msg["code"] = "500"
    # print(msg)
    return msg


# 获取一个公司信息
@bp.route("/getOneEInfo", methods=["POST"])
def getOneEInfo():
    msg = {
        "message": "",
        "type": "",
        "code": "",
    }
    eId = request.json["eId"]
    eModel = EnterpriseModel.query.filter_by(eId=eId).first()
    if eModel:
        msg["eId"] = eModel.eId
        msg["eContent"] = eModel.content
        msg["eSize"] = eModel.size
        msg["eNature"] = eModel.nature
        msg["eIndustry"] = eModel.industry
        msg["eAdvantage"] = eModel.advantage.split("-") if eModel.advantage else ""
        msg["contactName"] = eModel.contactName
        msg["contactPhone"] = eModel.contactPhone
        msg["contactEmail"] = eModel.contactEmail
        msg["contactAddress"] = eModel.contactAddress
        msg["businessName"] = eModel.businessName
        msg["businessSetTime"] = eModel.businessSetTime
        msg["businessRegCapital"] = eModel.businessRegCapital
        msg["businessLegalRepresentative"] = eModel.businessLegalRepresentative

        msg["message"] = "获取成功"
        msg["type"] = "success"
        msg["code"] = "200"
    else:
        msg["message"] = "没有该企业信息"
        msg["type"] = "error"
        msg["code"] = "500"

    return msg


# 获取所有公司信息
@bp.route("/getAllEInfo", methods=["GET"])
def getAllEInfo():
    msg = {
        "message": "",
        "type": "",
        "datas": [],
        "code": "",
    }

    enterpriseModel = EnterpriseModel.query.all()
    if enterpriseModel:
        for i in enterpriseModel:
            msg["datas"].append(
                {
                    "eId": i.eId,
                    "eContent": i.content,
                    "eSizeMin": i.size.split("-")[0],
                    "eSizeMax": i.size.split("-")[1],
                    "eIndustry": i.industry,
                    "eAdvantage": i.advantage.split("-"),

                    "contactName": i.contactName,
                    "contactEmail": i.contactEmail,
                    "contactAddress": i.contactAddress,
                    "contactPhone": i.contactPhone,

                    "businessName": i.businessName,
                    "businessRegCapital": i.businessRegCapital,
                    "businessLegalRepresentative": i.businessLegalRepresentative,
                    "businessSetTime": i.businessSetTime,

                })
            msg["message"] = "获取成功"
            msg["type"] = "success"
            msg["code"] = "200"
    else:
        msg["message"] = "没有企业信息"
        msg["type"] = "error"
        msg["datas"] = []
        msg["code"] = "500"
    return msg


# 获取热门岗位-9个-做主页的
@bp.route("/getAllJobInfo", methods=["GET"])
def getAllJobInfo():
    msg = {
        "message": "",
        "type": "",
        "datas": [],
        "code": "",
    }
    hotjobs = UserAndJobModel.query.group_by(UserAndJobModel.jobId).all()

    if hotjobs and len(hotjobs) > 9:
        limit = 0
        for i in hotjobs:
            jobModel = JobModel.query.filter_by(jobId=i.jobId).first()
            if jobModel.isPublishing == "true":
                limit = limit + 1
                msg["datas"].append({
                    "jobId": jobModel.jobId,
                    "jobName": jobModel.jobName,
                    "jobEdu": jobModel.jobEdu,
                    "jobAge": jobModel.jobAge,
                    "jobEx": jobModel.jobEx,
                    "jobSalary": jobModel.jobSalary,
                    "contactAddress": jobModel.hr_list[0].e_hr.contactAddress,
                    "eName": jobModel.hr_list[0].e_hr.businessName,
                    "eId": jobModel.hr_list[0].e_hr.eId,
                })
                msg["message"] = "获取成功"
                msg["type"] = "success"
                msg["code"] = "200"
            if limit == 9:
                break

    else:
        limit = 0
        jobModel = JobModel.query.all()
        for i in jobModel:
            if i.isPublishing == "true":
                limit = limit + 1
            msg["datas"].append({
                "jobId": i.jobId,
                "jobName": i.jobName,
                "jobEdu": i.jobEdu,
                "jobAge": i.jobAge,
                "jobEx": i.jobEx,
                "jobSalary": i.jobSalary,
                "contactAddress": i.hr_list[0].e_hr.contactAddress,
                "eName": i.hr_list[0].e_hr.businessName,
                "eId": i.hr_list[0].e_hr.eId,
            })
            msg["message"] = "获取成功"
            msg["type"] = "success"
            msg["code"] = "200"
            if limit == 9:
                break

    return msg


# 更新头像
@bp.route("/upAvatar", methods=["POST"])
def upAvatar():
    msg = {
        "message": "",
        "type": "",
        "code": ""
    }

    # 获取头像附带的数据
    # 获取上传头像的用户ID
    loginId = request.form["loginId"]
    # 获取用户的身份
    identity = request.form["identity"]
    if identity in ["user", "enterprise"]:
        # 请求中获取到上传的图片
        avatar_data = request.files.get('file')
        # 获取头像具体格式，jpg、jpeg、、、、
        avatar_type = avatar_data.content_type.split("/")
        # 随机头像在本地的名称
        avatar_name = hook.getRandom() + "." + avatar_type[1]
        # 保存头像的路径
        path = BASE_DIR / "static/img/"
        # 头像的绝对路径
        avatar_path = os.path.join(path, avatar_name)

        avatar_data.save(avatar_path)  # 保存
        if identity == "user":
            user = UserModel.query.filter_by(uId=loginId).first()
            if user:
                user.avatarName = avatar_name

                msg["message"] = "上传成功"
                msg["type"] = "success"
                msg["code"] = "200"
            else:
                msg["message"] = "身份非法"
                msg["type"] = "error"
                msg["code"] = "500"
        elif identity == "enterprise":
            hr = HRModel.query.filter_by(hrId=loginId).first()
            if hr:
                hr.e_hr.avatarName = avatar_name
                msg["message"] = "上传成功"
                msg["type"] = "success"
                msg["code"] = "200"
            else:
                msg["message"] = "身份非法"
                msg["type"] = "error"
                msg["code"] = "500"
        else:
            pass
    else:
        msg["message"] = "身份非法"
        msg["type"] = "error"
        msg["code"] = "500"

    return msg


# 获取用户头像
@bp.route("/getAvatar", methods=["POST"])
def getAvatar():
    '''
    设定数据库存储的是图片的名称+后缀
    则图片拼接是 BASE_DIR / "static" / "avatar_1.jpeg"
    '''
    # print(111)
    # 判断请求是否为空
    if request.json["identity"] is None:
        return "未登录,不用请求图片"
    else:
        # 判断身份企业还是用户
        if request.json["identity"] == "user":
            user = UserModel.query.filter_by(uId=request.json["loginId"]).first()
            # 拼接图片地址
            image_url = BASE_DIR / "static/img" / user.avatarName
            # image_url = BASE_DIR / "static/avatar_1.jpeg"
            # print(user.avatarName)
            with open(image_url, "rb") as f:
                image_data = f.read()
            image_res = make_response(image_data)
            image_res.headers['Content-Type'] = 'image.jpeg/png'
        elif request.json["identity"] == "enterprise":
            hr = HRModel.query.filter_by(hrId=request.json["loginId"]).first()
            # 拼接图片地址
            image_url = BASE_DIR / "static/img" / hr.e_hr.avatarName
            # image_url = BASE_DIR / "static/avatar_1.jpeg"
            # print(user.avatarName)
            with open(image_url, "rb") as f:
                image_data = f.read()
            image_res = make_response(image_data)
            image_res.headers['Content-Type'] = 'image.jpeg/png'


        else:
            return "非法身份"
    return image_res


# 退出登录
@bp.route("/loginOut", methods=["POST"])
def loginOut():
    msg = {
        "isDelete": ""
    }
    loginId = request.json["loginId"]
    if loginId:
        res = redisDB.delRedisOne(loginId)
        if res:
            msg["isDelete"] = "true"
        else:
            msg["isDelete"] = "false"
    else:
        msg["isDelete"] = "true"
    return msg


# 查看redis用户的登录状态是否过期
@bp.route("/getLoginState", methods=["POST"])
def getLoginState():
    msg = {
        "message": "",
        "type": "",
        "code": "",
        "isLogin": ""
    }
    loginId = request.json["loginId"]
    if loginId:
        # token = request.json["token"]
        res = redisDB.handle_redis_token(loginId)
        if res is not None:
            msg["isLogin"] = "true"
            msg["code"] = "200"
            msg["message"] = "登录时效未过期"
            msg["type"] = "success"
        else:
            msg["code"] = "200"
            msg["message"] = "登录时效过期"
            msg["type"] = "success"
            msg["isLogin"] = "false"
    else:
        msg["code"] = "500"
        msg["message"] = "非法ID"
        msg["type"] = "error"
        msg["isLogin"] = "false"

    return msg


# 获取主页banner，但现在不知道怎么从后台传多张图片
@bp.route("/getBanner", methods=["POST", "GET"])
def getBanner():
    bannerName = request.json["bannerName"]
    # 拼接图片地址
    image_url = BASE_DIR / "static/banner" / bannerName
    # image_url = BASE_DIR / "static/avatar_1.jpeg"
    # print(user.avatarName)
    with open(image_url, "rb") as f:
        image_data = f.read()
    image_res = make_response(image_data)
    image_res.headers['Content-Type'] = 'image.jpeg/png'
    return image_res


# 获取主页岗位菜单
@bp.route("/getHomeMenu", methods=["GET"])
def getHomeMenu():
    msg = {
        "message": "",
        "type": "",
        "code": "",
        "menu_list": []
    }
    try:

        msg["menu_list"] = constructMenuTrees("0")
        msg["message"] = "获取成功"
        msg["code"] = "200"
        msg["type"] = "success"
    except SQLAlchemyError as e:
        msg["message"] = "获取失败"
        msg["type"] = "error"
        msg["code"] = "500"
        print(e)
    return msg


# 登录
@bp.route("/login", methods=["POST", "GET"])
def login():
    msg = {
        "message": "",
        "type": "",
        "code": ""
    }

    try:
        role = request.json["role"]
        email = request.json["email"]
        password = request.json["password"]
        # 企业
        if role == "enterprise":
            hr = HRModel.query.filter_by(hrEmail=email).first()
            if hr:
                # 存在,则对比密码
                if check_password_hash(hr.hrPassword, password):
                    msg["loginId"] = hr.hrId
                    msg["identity"] = "enterprise"
                    msg["token"] = _generate_token(hr.hrId)
                    msg["message"] = "登录成功"
                    msg["type"] = "success"
                    msg["code"] = "200"
                    # 账号密码正确，在redis中设置在线时间
                    redisDB.handle_redis_token(hr.hrId, msg["token"])
                else:
                    msg["message"] = "密码错误"
                    msg["code"] = "500"
                    msg["type"] = "error"
            else:
                msg["message"] = "用户不存在"
                msg["type"] = "error"
                msg["code"] = "500"
        # 用户
        elif role == "user":
            user = UserModel.query.filter_by(email=email).first()
            # 判断是否存在该用户
            if user:
                # 存在,则对比密码
                if check_password_hash(user.password, password):
                    msg["loginId"] = user.uId
                    msg["identity"] = "user"
                    msg["token"] = _generate_token(user.uId)
                    msg["message"] = "登录成功"
                    msg["type"] = "success"
                    msg["code"] = "200"
                    # 账号密码正确，在redis中设置在线时间
                    redisDB.handle_redis_token(user.uId, msg["token"])
                else:
                    msg["message"] = "密码错误"
                    msg["type"] = "error"
                    msg["code"] = "500"
            else:
                msg["message"] = "用户不存在"
                msg["type"] = "error"
                msg["code"] = "500"
        # 管理员
        elif role == "admin":
            admin = AdminModel.query.filter_by(adminEmail=email).first()
            if admin:
                if check_password_hash(admin.adminPassword, password):
                    msg["loginId"] = admin.adminId
                    msg["identity"] = "admin"
                    msg["token"] = _generate_token(admin.adminId)
                    msg["message"] = "登录成功"
                    msg["type"] = "success"
                    msg["code"] = "200"
                    # 账号密码正确，在redis中设置在线时间
                    redisDB.handle_redis_token(admin.adminId, msg["token"])
                else:
                    msg["message"] = "密码错误"
                    msg["type"] = "error"
                    msg["code"] = "500"
            else:
                msg["message"] = "用户不存在"
                msg["type"] = "error"
                msg["code"] = "500"
    except SQLAlchemyError as e:
        print(e)

    return msg


# 注册
@bp.route("/register", methods=["POST"])
def register():
    msg = {
        "code":'',
        "message": "",
        "type": "",
    }

    try:
        if request.json["role"] == "enterprise":
            email = request.json["email"]
            hrEmail = HRModel.query.filter_by(hrEmail=email).first()
            if hrEmail:
                msg["code"] = "500"
                msg["message"] = "邮箱已被注册"
                msg["type"] = "error"
            else:
                eName = request.json["eName"]
                e = EnterpriseModel.query.filter_by(businessName=eName).first()
                # 判断是否存在该公司
                # 存在则加入这家公司
                # print(e)
                if e:
                    hrId = str(int(time.time() * 1000))
                    name = request.json["name"]
                    password = request.json["password_1"]
                    hr = HRModel(hrId=hrId, hrAvatarName="hr_1.jpeg", hrName=name, hrEmail=email,
                                 hrLevel="招聘者",
                                 hrPassword=generate_password_hash(password),
                                 e_hr_id=e.eId)
                    db.session.add(hr)
                    db.session.commit()
                    msg["code"] = "200"
                    msg["message"] = "注册成功"
                    msg["type"] = "success"
                # 不存在则添加一个新公司
                # else:
                #     eId = str(int(time.time() * 1000))
                #     hrName = request.json["name"]
                #     newE = EnterpriseModel(eId=eId, avatarName="iwu.jpeg", businessName=eName, contactName=hrName,
                #                            contactEmail=hrEmail)
                #     db.session.add(newE)
                #     db.session.commit()
                #     msg["message"] = "注册成功"
                #     msg["type"] = "success"

        elif request.json["role"] == "user":
            userEmail = request.json["email"]
            user = UserModel.query.filter_by(email=userEmail).first()
            if user:
                msg["code"] = "500"
                msg["message"] = "邮箱已被注册"
                msg["type"] = "error"
            else:
                id = str(int(time.time() * 1000))
                name = request.json["name"]
                email = request.json["email"]
                password = request.json["password_1"]
                user = UserModel(uId=id,
                                 avatarName="avatar_1.jpeg",
                                 # gander="null",
                                 # newAddress="-",
                                 # birthAddress="-",

                                 name=name,
                                 email=email,
                                 password=generate_password_hash(password))
                db.session.add(user)
                db.session.commit()
                msg["code"]="200"
                msg["message"] = "注册成功"
                msg["type"] = "success"
    except IntegrityError as e:
        msg["message"] = "注册失败"
        msg["type"] = "error"
        print(e)

    return msg


# 获取所有公司的eId和名称
@bp.route("/getAllE", methods=["GET"])
def getAllE():
    msg = []
    try:
        es = EnterpriseModel.query.all()
        if es:
            for i in es:
                msg.append({
                    'eId': i.eId,
                    'eName': i.businessName
                })
        else:
            msg = []

    except Exception as e:
        print(e)

    return msg


def constructMenuTrees(parentId="0"):
    '''
    通过递归实现根据父ID查找子菜单,如果传入用户id则只查询该用户的权限否则查询所有权限,一级菜单父id默认是0
    1.根据父ID获取该菜单下的子菜单或权限
    2.遍历子菜单或权限，继续向下获取，直到最小级菜单或权限
    3.如果没有遍历到，返回空的数组，有返回权限列表
    :param user_id:
    :param parentId:
    :return:dict
    '''

    menu_data = HomeMenuModel.query.filter(HomeMenuModel.father == parentId).order_by('id').all()
    menu_dict = menu_to_dict(menu_data)
    if len(menu_dict) > 0:
        data = []
        for menu in menu_dict:
            menu['child'] = constructMenuTrees(menu['id'])
            data.append(menu)
        return data
    return []


def menu_to_dict(result):
    '''
        格式化菜单字段显示顺序
        :param result:
        :return:
        '''
    data = []
    for menu in result:
        child = {
            "id": menu.children,
            "name": menu.name,
            # "parent_id": menu.parent_id,

        }
        data.append(child)
    return data


def jobIndustryMenuTrees(parentId="0"):
    '''
    通过递归实现根据父ID查找子菜单,如果传入用户id则只查询该用户的权限否则查询所有权限,一级菜单父id默认是0
    1.根据父ID获取该菜单下的子菜单或权限
    2.遍历子菜单或权限，继续向下获取，直到最小级菜单或权限
    3.如果没有遍历到，返回空的数组，有返回权限列表
    :param user_id:
    :param parentId:
    :return:dict
    '''

    menu_data = HomeMenuModel.query.filter(HomeMenuModel.father == parentId).order_by('id').all()
    menu_dict = jobIndustryMenu_to_dict(menu_data)
    if len(menu_dict) > 0:
        data = []
        for menu in menu_dict:
            menu['children'] = jobIndustryMenuTrees(menu['id'])
            if len(menu["id"]) < 4:
                if menu["id"][0:2] == "10" or len(menu["id"]) < 3:
                    data.append(menu)
        return data
    return []


def jobIndustryMenu_to_dict(result):
    '''
        格式化菜单字段显示顺序
        :param result:
        :return:
        '''
    data = []
    for menu in result:
        children = {
            "id": menu.children,
            "value": menu.name,
            "label": menu.name,
            # "parent_id": menu.parent_id,
        }
        data.append(children)
    return data


def generate_jwt(payload, expiry, secret=None):
    """
    生成jwt
    :param payload: dict 载荷
    :param expiry:  datatime 有效期
    :param secret:  盐
    :return:  返回token
    """

    if "expiry" not in payload:
        payload["expiry"] = expiry

    # 判断盐是否存在
    if secret:
        secret = current_app.config["SECRET_KEY"]

    # 生成token  jwt.encode
    token = jwt.encode(payload, secret, algorithm="HS256")
    return token


def verify_jwt(token, secret=None):
    """
    校验token
    :param token:  token值
    :param secret:  盐
    :return:  payload 载荷
    """

    # 判断盐是否存在
    if not secret:
        secret = current_app.config["SECRET_KEY"]

    try:
        # 校验token jwt.decode

        payload = jwt.decode(token, secret, algorithms="HS256")
    except Exception as e:
        print("错误信息>>", e)
        # 校验失败返回None
        payload = None
    return payload


def _generate_token(user_id):
    """
    生成token
    :param user_id: 用户id
    :return: token
    """
    # 获取盐
    secret = current_app.config['SECRET_KEY']
    # 定义过期时间 两小时
    expiry = datetime.now() + timedelta(hours=2)
    # 生成token
    token = generate_jwt({"user_id": user_id}, str(expiry), secret)
    return token
